<?php

namespace App\Console\Commands\Clear;

use App\Kuafu\Export\Model\ExportDownloadModel;
use Illuminate\Console\Command;
use Kuafu\File\FileUtil;

class ExportDownloads extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clear:export-downloads-resource';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导出文件下载中心-30天自动删除历史记录及资源';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $ids = $paths = [];
        $fileTypes = [
            ExportDownloadModel::FILE_TYPE_APP_SOURCE_MATERIAL_TEMPLATE,
            ExportDownloadModel::FILE_TYPE_APP_DISTRIBUTION_QRCODE,
            ExportDownloadModel::FILE_TYPE_WEB_TIGER_WORK_ORDER,
            ExportDownloadModel::FILE_TYPE_WEB_TIGER_APPRAISE,
            ExportDownloadModel::FILE_TYPE_WEB_ALBUM_RESOURCE,
            ExportDownloadModel::FILE_TYPE_WEB_ACTIVITY_MATERIAL,
        ];
        ExportDownloadModel::query()
            ->whereIn('fileType', $fileTypes)
            ->where('expireTime', '<', time())
            ->chunk(500, function ($data) use ($ids, $paths) {
                foreach ($data as $item) {
                    $ids[] = $item['id'];
                    if ($item['path']) {
                        $paths[] = $item['path'];
                    }
                }
                if ($ids) {
                    ExportDownloadModel::query()
                        ->whereIn('id', $ids)
                        ->update(['isDeleted' => 1]);//批量删除记录
                    if ($paths) {
                        FileUtil::deleteObjects($paths);//批量删除oss资源
                    }
                }
            });
    }
}
